package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"red-book-pub/cache"
	"red-book-pub/model"
	"strconv"
	"time"
)

func CreateRedBook(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	address := c.PostForm("address")
	img := c.PostForm("img")
	if title == "" || content == "" || address == "" || img == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空字段",
		})
		return
	}
	data := model.RedBook{
		Title:   title,
		Content: content,
		Address: address,
		Img:     img,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	redis_key := "red_book_" + strconv.Itoa(int(data.ID))
	jsonData, _ := json.Marshal(data)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func DetailRedBook(c *gin.Context) {
	id := c.Query("id")
	var redbook model.RedBook
	err := model.DB.Where("id=?", id).First(&redbook).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "详情失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "详情获取成功",
		"data": redbook,
	})
	return
}

func DelRedBook(c *gin.Context) {
	id := c.Query("id")
	var redbook model.RedBook
	err := model.DB.Where("id=?", id).Delete(&redbook).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "red_book_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func ListRedBook(c *gin.Context) {
	var list []model.RedBook
	redis_key := "list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "获取成功",
		"data": list,
	})
	return

}
